<?php
namespace app\app\controller;

use app\common\model\BabyGrowLog;
use app\common\model\Message;
use think\Db;
use think\Exception;
use think\Validate;

class Comment extends Base
{
    /**
     * 评论
     * @return \think\response\Json
     * @throws \Exception
     */
    public function comment(){
        try{
            Db::startTrans();
            $input = input('post.',null,'trim');
            $input['operate_id'] = $this->parent_id;
            $model = new \app\common\model\Comment();
            $model->allowField(true)->force()->save($input);
            $article = \app\common\model\Article::get($model['related_id']);
            if(!empty($article) && $article['type'] == 3){
                $message = new Message();
                $message->type = 1;
                $message->parent_id = $article['parent_id'];
                $message->operate_id = $input['operate_id'];
                $message->relate_id = $model['id'];
                $message->save();
            }

            Db::commit();
            return $this->succeed('操作成功',[]);
        }catch (Exception $e){
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 回复
     * @return \think\response\Json
     */
    public function answer(){
        try{
            Db::startTrans();
            $input = input('post.',null,'trim');
            $comment = \app\common\model\Comment::get($input['id']);
            $comment->answer = $input['answer'];
            $comment->save();
            $article = \app\common\model\Article::get($comment['related_id']);
            if(!empty($article) && $article['type'] == 3){
                $message = new Message();
                $message->type = 2;
                $message->parent_id = $comment['operate_id'];
                $message->operate_id = $article['parent_id'];
                $message->relate_id = $comment['id'];
                $message->save();
            }

            Db::commit();
            return $this->succeed('操作成功',[]);
        }catch (Exception $e){
            Db::rollback();
            return $this->fail($e->getMessage());
        }
    }


}
